<?php

namespace App\Admin\Renderable;

use App\Imports\ClueImport;
use App\Imports\CrmUserImport;
use App\Models\Administrator;
use App\Models\Clue;
use App\Models\MediaSource;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;


class ImportClueForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理请求
     *
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        // id转化为数组
        $url = data_get($input, 'file');
        $source = data_get($input, 'source');
        if (!$source)
            return $this->response()->error('找不到媒介来源');

        if (!$url)
            return $this->response()->error('找不到上传的文件');

        try {
            $import = new ClueImport($source);
            Excel::import($import, $url, 'public');

            Storage::disk('public')->delete($url);
            if ($import->errorMessage)
                return $this->response()->error($import->errorMessage);
            return $this->response()->success("线索导入成功,创建了{$import->count}条")->refresh();
        } catch (\Exception $exception) {
            return $this->response()->error($exception->getMessage());
        }

    }

    public function form()
    {
        $fileUrl = Storage::disk('public')->url("导入线索模板.csv");
        $this->disableResetButton();
        $alert = Alert::make("导入....");
        $this->html($alert);
        $options = MediaSource::toOptions();
        $this->select('source', '数据来源')
            ->options($options)
            ->required();
        $this->file('file', '文件')
            ->accept('xlsx,xls,csv')
            ->move("cache_files")
            ->autoUpload()
            ->help("下载导入模板: <a href='$fileUrl' target='_blank'>导入线索模板.csv</a>")
            ->required();

    }
}
